package com.data.dbdao;

import com.data.bean.Account;
import com.data.util.FinalStringUtils;
import com.data.util.LoginMethodUtils;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Repository
public class RegisetdbDao extends BaseDao {
    /**
     * 根据账号(账号，邮箱，手机号)来检测邮箱是否被占用
     *
     * @param account
     * @return
     */
    public boolean checkEmailDao(String res, String account) {
        StringBuilder tempHql = new StringBuilder("from Account where ");
        String hql = LoginMethodUtils.getHql(tempHql, res);
        return super.findMassageDao(hql, account).size() > 0;
    }

    /**
     * 如果是带有id注册
     *
     * @param res
     * @param account
     * @param id
     * @return
     */
    public boolean checkEmailDao(String res, String account, String id) {
        StringBuilder tempHql = new StringBuilder("from Account where ");
        String hql = LoginMethodUtils.getHql(tempHql, res);
        hql += " and id!=?";
        return super.findMassageDao(hql, account, id).size() > 0;

    }

    /**
     * 保存或者更新数据
     *
     * @param account
     * @return
     */
    public Boolean saveRegistDao(Account account) {
        return super.saveMassageDao(account);
    }

    /**
     * 邮箱激活检测,根据邮箱，激活码，邮箱状态来确定是否激活
     *
     * @param email
     * @param code
     * @return
     */
    public Account activeEmailDao(String email, String code) {
        String hql = "from Account where email=? and code=? and state=?";
        List<Account> list = (List<Account>) super.findMassageDao(hql, email, code, FinalStringUtils.STATE_DEFAULT);
        if (list != null && !list.isEmpty()) {
            return list.get(0);
        } else
            return null;
    }

    /**
     * 修改账号状态
     *
     * @return
     */
    public boolean changeAccountState(String email) {
        String hql = "update Account set state=?,code=? where id=?";
        //设置邮箱状态为激活状态
        return super.updateOneMssageDao(hql, FinalStringUtils.STATE_ACTIVE, null, email);
    }


    /**
     * 更换邮箱,创建时间，将来的邮箱激活时间
     *
     * @param account
     * @return
     */
    public boolean changeEmailDao(Account account) {
        return super.saveMassageDao(account);
    }

    /**
     * 重发邮件时候，重置账号的状态
     *
     * @param id
     * @param email
     * @param code
     * @param date
     * @return
     */
    public boolean changeEmailAndCodeDao(String id, String email, String code, Date date) {
        String hql = "update Account set code=?,ctime=? where id=? and email=? and state=?";
        return updateOneMssageDao(hql, code, date, id, email, FinalStringUtils.STATE_DEFAULT);
    }
}
